<template>
  <div id="table">
    <div id="top">
      <p>角色管理</p>
      <div>
        <el-button type="primary" plain @click="add">添加</el-button>
        <el-button type="info" plain @click="batchDelSure">批量删除</el-button>
        <el-button type="warning" round @click="refresh">刷新</el-button>
        <!--<div>
          选择图片
          <input type="file" accept="image/*" @change="chooseImg" />
          预览图片
          <canvas ref="imgPreview" height="0" width="0"></canvas>
          提交图片
          <button @click="uploadImg">提交图片</button>
          通过后台返回的url向文件服务器请求图片
          <img :src="imgUrlFromServer">
        </div>-->
      </div>
    </div>
    <el-dialog :title="tit" :visible.sync="addVisible" width="30%" :before-close="handleClose">
      <el-form label-width="80px" :model="from">
        <el-form-item label="角色名称" :required="true">
          <el-input v-model="from.name" :maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="职能描述" :required="true">
          <el-input type="textarea" v-model="from.function" :rows="3" :maxlength="50" resize="none" placeholder="职能描述不超过50个字"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" :required="true">
          <el-switch v-model="from.enable">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="changeRole">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="tit" :visible.sync="jurisVisible" width="30%">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedjurisData" @change="handleCheckedjurisDataChange">
        <el-checkbox v-for="(v,i) in jurisData" :label="v.path" :key="i">{{v.name}}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="jurisVisible=false">取 消</el-button>
        <el-button type="primary" @click="changeJuris">确 定</el-button>
      </span>
    </el-dialog>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" :border="true" @selection-change="selectCheck">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="50">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="150">
      </el-table-column>
      <el-table-column prop="function" label="职能" width="200">
      </el-table-column>
      <el-table-column prop="num" label="成员数" width="100">
      </el-table-column>
      <el-table-column prop="addtime" label="创建时间" width="300">
      </el-table-column>
      <el-table-column prop="enable" label="是否启用" width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" @change="changeEnable(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button @click="editJuris(scope.row)" type="text" size="small">权限管理</el-button>
          <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="delSure(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div id="page">
      <el-pagination background layout="prev, pager, next" :total="allData.length" :page-size="eachNum" :current-page.sync="nowPage">
      </el-pagination>
    </div>
  </div>
</template>

<script>

import date from '../../components/package';

let allJuris = [{ "path": "/homeframe/home", "name": "首页" }, { "path": "/homeframe/goods", "name": "商品" }, { "path": "/homeframe/order", "name": "订单" }, { "path": "/homeframe/users", "name": "用户" }, { "path": "/homeframe/promotion", "name": "促销" }, { "path": "/homeframe/operate", "name": "运营" }, { "path": "/homeframe/statistics", "name": "统计" }, { "path": "/homeframe/jurisdiction", "name": "权限" }];

let jurisModel = [];
allJuris.filter((item) => {
  jurisModel.push(item.path)
})

export default ({
  data() {
    return {
      allData: [],
      nowPage: 1,
      eachNum: 8,
      addVisible: false,
      jurisVisible: false,
      from: {
        name: '',
        function: '',
        enable: true,
      },
      batchDelFrom: {},
      tit: '',
      checkAll: false,
      checkedjurisData: [],
      isIndeterminate: true,
      jurisData: allJuris,
      editRoleid: ''
    };
  },
  mounted() {
    this.getAllRole();
  },
  computed: {
    tableData() {
      return this.allData.slice((this.nowPage - 1) * this.eachNum, this.nowPage * this.eachNum);
    }
  },
  methods: {
    getAllRole() {
      this.$axios({
        url: '/jurisdiction/getallrole',
        method: 'get'
      }).then((res) => {
        res.data.data.filter((v) => {
          v.addtime = date.dateFn(v.addtime);
          if (v.function == '') {
            v.function = '暂无描述'
          };
          if (v.enable == '是') {
            v.enable = true;
          } else {
            v.enable = false;
          };
          if (!v.roleid) {
            v.num = 0;
          }
        });
        this.allData = res.data.data;
        console.log(this.allData)
      })
    },
    changeEnable(val) {
      if (val.enable) {
        val.enable = '是'
      } else {
        val.enable = '否'
      }
      this.$axios({
        url: '/jurisdiction/changeEnable',
        method: 'post',
        data: val
      }).then(() => {
        if (val.enable == '是') {
          this.$message({
            message: '启用成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: '禁用成功',
            type: 'warning'
          });
        }
        this.getAllRole();
      })
    },
    delSure(data) {
      this.$confirm('确认删除该角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.del(data);
      })
    },
    del(data) {
      console.log(data)
      if (data.num) {
        this.$message({
          message: '该角色下有成员，无法删除',
          type: 'warning'
        });
      } else {
        this.$axios({
          url: '/jurisdiction/delrole',
          method: 'post',
          data: data
        }).then(() => {
          this.getAllRole();
          this.$message({
            message: '角色删除成功',
            type: 'success'
          });
        })
      }
    },
    handleClose() {
      this.$confirm('确认关闭？', {
        callback: (action, instance) => {
          if (action == 'cancel') {
            this.addVisible = true;
          } else if (action == 'confirm') {
            this.addVisible = false;
            this.from = {
              name: '',
              function: '',
              enable: true
            };
          }
        }
      })
    },
    changeRole() {
      if (this.from.type == 'add') {
        this.addRole();
        console.log('add')
      } else {
        this.editRole();
      }
    },
    add() {
      this.tit = '添加角色';
      this.addVisible = true;
      this.from.type = 'add';
    },
    addRole() {
      if (this.from.name == '' || this.from.function == '') {
        this.$message({
          message: '有必填项未填写',
          type: 'error'
        });
      } else {
        this.addVisible = false;
        this.$axios({
          url: '/jurisdiction/addrole',
          method: 'post',
          data: this.from
        }).then(() => {
          this.getAllRole();
          this.from = {
            name: '',
            function: '',
            enable: true
          };
          this.$message({
            message: '添加成功',
            type: 'success'
          });
        })
      }
    },
    edit(data) {
      this.tit = '修改角色';
      this.addVisible = true;
      this.from = { ...data }
      //this.from = data;
      this.from.type = 'edit';
    },
    editRole() {
      this.addVisible = false;
      this.$axios({
        url: '/jurisdiction/editrole',
        method: 'post',
        data: this.from
      }).then(() => {
        this.getAllRole();
        this.from = {
          name: '',
          function: '',
          enable: true
        };
        this.$message({
          message: '修改成功',
          type: 'success'
        });
      })
    },
    refresh() {
      this.getAllRole();
      this.$message({
        message: '已刷新',
        type: 'success'
      });
    },
    handleCheckAllChange(val) {
      this.checkedjurisData = val ? jurisModel : [];
      this.isIndeterminate = false;
    },
    handleCheckedjurisDataChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.jurisData.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.jurisData.length;
    },
    editJuris(data) {
      this.jurisVisible = true;
      this.editRoleid = data.id;
      this.$axios({
        url: '/jurisdiction/menu',
        method: 'get',
        params: data
      }).then((res) => {
        let arr = [];
        if (res.data.data[0].jurisdiction) {
          JSON.parse(res.data.data[0].jurisdiction).filter((item) => {
            arr.push(item.path);
          })
        }
        this.checkedjurisData = arr;
      })
    },
    changeJuris() {
      let arr = [];
      allJuris.filter((item) => {
        for (let i = 0; i < this.checkedjurisData.length; i++) {
          if (item.path == this.checkedjurisData[i]) {
            let obj = {};
            obj.path = item.path;
            obj.name = item.name;
            arr.push(obj);
          }
        }
      });
      this.$axios({
        url: '/jurisdiction/editmenu',
        method: 'post',
        data: {
          id: this.editRoleid,
          jurisdiction: JSON.stringify(arr)
        }
      }).then(() => {
        this.jurisVisible = false;
        this.$message({
          message: '权限修改成功',
          type: 'success'
        });
      })
    },
    batchDelSure() {
      this.$confirm('确认删除所选角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let str = '';
        for (let i = 0; i < this.batchDelFrom.length; i++) {
          if (this.batchDelFrom[i].num) {
            str = str + `"${this.batchDelFrom[i].name}"` + " "
          }
        }
        if (str) {
          console.log(str)
          this.$message({
            message: '角色:' + str + '下存在成员，无法删除',
            type: 'warning'
          })
        } else {
          this.batchDel();
        }
      })
    },
    batchDel() {
      this.$axios({
        url: '/jurisdiction/batchdelrole',
        method: 'post',
        data: this.batchDelFrom
      }).then(() => {
        this.getAllRole();
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      })
    },
    selectCheck(selection) {
      this.batchDelFrom = selection;
    },
    //处理图片上传
    chooseImg(event) {
      //获取图片信息
      let file = event.target.files[0]
      this.name = file.name;
      let reader = new FileReader()
      let img = new Image()
      // 读取图片
      reader.readAsDataURL(file)
      // 读取完毕后的操作
      reader.onloadend = (e) => {
        img.src = e.target.result
        // 这里的e.target就是reader
        // console.log(reader.result)
        // reader.result就是图片的base64字符串
        this.base64 = reader.result
      }
      // 预览图片
      let canvas = this.$refs['imgPreview']
      let context = canvas.getContext('2d')
      img.onload = () => {
        img.width = 100
        img.height = 100
        // 设置canvas大小
        canvas.width = 100
        canvas.height = 100
        // 清空canvas
        context.clearRect(0, 0, 100, 100)
        // 画图
        context.drawImage(img, 0, 0, 100, 100)
      }
    },
    uploadImg() {
      this.$axios({
        url: '/uploadImg',
        method: 'post',
        data: {
          base64: this.base64,
          name: this.name
        }
      }).then((res) => {
        this.imgUrlFromServer = res.data.imgUrl
      })
    }
  }
})
</script>

<style lang="less" scoped>
#top {
  height: 40px;
  margin-bottom: 10px;
  line-height: 40px;
  p {
    float: left;
  }
  div {
    float: right;
  }
}
#table {
  overflow-y: hidden;
  .el-table {
    min-height: 505px;
  }
}
/deep/ .cell {
  text-align: center;
}
#page {
  margin-top: 20px;
  width: 100%;
  text-align: center;
}
</style>
